package com.situ.skymallproductcategoryapi.api;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.model.ProductCategory;
import com.situ.service.ProductCategoryService;
import com.situ.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.xml.crypto.Data;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping(value = "/api/v1/productCategories", produces = "application/json;charset=utf-8")
public class ProductCategoryApi {
    public ProductCategoryService productCategoryService;

    @Autowired
    public ProductCategoryApi(ProductCategoryService productCategoryService) {
        this.productCategoryService = productCategoryService;
    }

    /*
      前台查询所有商品类别
      @return 商品类别列表
     */
    @GetMapping("/list")
    public ResponseEntity<JsonResult<?>> getList() {
        List<ProductCategory> list = productCategoryService.getList();
        if (list == null) {
            return ResponseEntity.ok(JsonResult.fail("暂无商品分类"));
        } else {
            return ResponseEntity.ok(JsonResult.success(list));
        }
    }

    /*
      后台查询商品类别
      @param current 当前页码
      @param size 每页数量
      @param search 查询条件
      @return 商品类别列表
     */
    @GetMapping
    public ResponseEntity<JsonResult<?>> getList(@RequestParam(defaultValue = "1") Integer current,
                                                 @RequestParam(defaultValue = "5") Integer size,
                                                 ProductCategory search) {
        Page<ProductCategory> page = new Page<>(current, size);
        page = productCategoryService.getList(page, search);
        if (page == null) {
            return ResponseEntity.ok(JsonResult.fail("暂无商品分类"));
        } else {
            return ResponseEntity.ok(JsonResult.success(page));
        }
    }

    /*
      获取商品类别树形列表
      @return 商品类别树形列表
     */
    @GetMapping("/tree")
    public ResponseEntity<JsonResult<?>> getTreeList() {
        List<ProductCategory> list = productCategoryService.getTreeList();
        if (list == null) {
            return ResponseEntity.ok(JsonResult.fail("暂无商品分类"));
        } else {
            return ResponseEntity.ok(JsonResult.success(list));
        }
    }

    /*
      获取商品类别详情
      @param id 商品类别ID
      @return 商品类别详情
     */
    @GetMapping("/id/{id}")
    @SentinelResource(value ="productCategories-api-getById" ,blockHandler = "blockGetById",fallback = "fallbackGetById")
    public ResponseEntity<JsonResult<?>> getById(@PathVariable Integer id) {
        ProductCategory productCategory = productCategoryService.getById(id);

        //模拟异常
//        Random random=new Random();
//        int i=random.nextInt(10);
//        if(i<5){
//            throw new RuntimeException("出现异常");
//        }
        //以上为模拟异常
        if (productCategory == null) {
            return ResponseEntity.ok(JsonResult.fail("商品分类不存在"));
        } else {
            return ResponseEntity.ok(JsonResult.success(productCategory));
        }
    }
    //限流或熔断
    public ResponseEntity<JsonResult<?>> blockGetById(Integer id, BlockException blockException){
        if(blockException instanceof FlowException){
            return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).body(JsonResult.fail("服务器繁忙0--限流"));
        }else if(blockException instanceof DegradeException){
            return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).body(JsonResult.fail("服务器繁忙0--熔断"));
        }
        return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).body(JsonResult.fail("服务器繁忙1--限流或熔断"));
    }
    //        //既不是熔断也不是限流,普通业务异常
    public ResponseEntity<JsonResult<?>> fallbackGetById(Integer id, Throwable throwable){
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(JsonResult.fail("服务器繁忙2---普通业务异常"));
    }




    /*
      保存商品类别
      @param productCategory 商品类别
      @return 是否保存成功
     */
    @PutMapping
    public ResponseEntity<JsonResult<?>> save(@RequestBody ProductCategory productCategory) {
        boolean result = productCategoryService.save(productCategory);
        if (result) {
            return ResponseEntity.ok(JsonResult.success("保存成功"));
        } else {
            return ResponseEntity.ok(JsonResult.fail("保存失败"));
        }
    }

    /*
      更新商品类别
      @param productCategory 待更新的商品类别
      @return 是否更新成功
     */
    @PostMapping
    public ResponseEntity<JsonResult<?>> update(@RequestBody ProductCategory productCategory) {
        boolean result = productCategoryService.updateById(productCategory);
        if (result) {
            return ResponseEntity.ok(JsonResult.success("更新成功"));
        } else {
            return ResponseEntity.ok(JsonResult.fail("更新失败"));
        }
    }

    /*
      删除商品类别
      @param id 待删除的商品类别ID
      @return 是否删除成功
     */
    @DeleteMapping("/id/{id}")
    public ResponseEntity<JsonResult<?>> deleteById(@PathVariable Integer id) {
        boolean result = productCategoryService.deleteById(id);
        if (result) {
            return ResponseEntity.ok(JsonResult.success("删除成功"));
        } else {
            return ResponseEntity.ok(JsonResult.fail("删除失败"));
        }
    }

    /*
      切换展示商品类别（开启/关闭）
      @param id 待改变状态的商品类别ID
      @return 是否切换成功
     */
    @PostMapping("/toggleShow/{id}")
    public ResponseEntity<JsonResult<?>> toggleShow(@PathVariable Integer id) {
        boolean result = productCategoryService.toggleShow(id);
        if (result) {
            return ResponseEntity.ok(JsonResult.success("切换成功"));
        } else {
            return ResponseEntity.ok(JsonResult.fail("切换失败"));
        }
    }
}
